package com.skyline.energy.jdbc.impl.queued;

import javax.sql.DataSource;

import com.skyline.common.concurrent.queue.Task;
import com.skyline.common.concurrent.queue.TaskParameters;
import com.skyline.common.concurrent.queue.TaskRepository;
import com.skyline.energy.jdbc.Dialect;
import com.skyline.energy.jdbc.JdbcDataAccessor;
import com.skyline.energy.jdbc.impl.PreparedStatementCallback;
import com.skyline.energy.jdbc.impl.QueryCallback;
import com.skyline.energy.jdbc.impl.SimpleJdbcDataAccessor;

/**
 * JdbcDataAccessor的高并发实现。采用队列方式，多线程共享数据，以牺牲一定数据一致性为代价，获得较高的并发处理性能。
 * 
 * @author wuqh
 * 
 */
public class QueuedJdbcDataAccessor extends SimpleJdbcDataAccessor implements JdbcDataAccessor {
	private final SimpleJdbcDataAccessor dataAccessor = new SimpleJdbcDataAccessor();

	private long timeout = 0L;

	@Override
	public <T> T execute(String sql, int fetchSize, boolean returnKeys,
			PreparedStatementCallback<T> action, Object... args) {
		if ((action instanceof QueryCallback<?>) == false) {
			return dataAccessor.execute(sql, fetchSize, returnKeys, action, args);
		}

		TaskParameters parameters = new JdbcQueryTaskParameters(sql, fetchSize, returnKeys, action,
				args);

		Task task = new JdbcQueryTask(dataAccessor);

		TaskRepository.addTask(task, parameters);

		T result = TaskRepository.processTask(task, parameters, timeout);

		return result;
	}

	public void setTimeout(long timeout) {
		this.timeout = timeout;
	}

	@Override
	public void setDataSource(DataSource dataSource) {
		dataAccessor.setDataSource(dataSource);
	}

	@Override
	public void setDialect(Dialect dialect) {
		dataAccessor.setDialect(dialect);
	}

}
